package com.jielin.handling.controller.goods;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.dynamodbv2.xspec.B;
import com.github.pagehelper.PageInfo;
import com.jielin.handling.Annotation.MyPower;
import com.jielin.handling.bean.AppResult;
import com.jielin.handling.entity.goods.Belongings;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.page.DataGrid;
import com.jielin.handling.service.goods.GoodsService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by wangjienice on 2019/3/19.
 */
@CrossOrigin
@RestController
@RequestMapping("/goods/")
@Slf4j
@MyPower(name = "嫌疑人随身物品模块", url = "/goods")
public class GoodsController {
    @Autowired
    GoodsService goodsService;


    /**
     * 嫌疑人随身物品照片
     */
    @MyPower(name = "添加嫌疑人随身物品照片", url = "/addGoods")
    @ResponseBody
    @RequestMapping("/addGoods")
    public AppResult addGoods(MultipartFile file, String fileString, String suspectId) {
        AppResult appResult = new AppResult();
        JSONObject data = new JSONObject();
        log.info("file:{}", JSONObject.toJSONString(file));
        log.info("fileString:{}", JSONObject.toJSONString(fileString));
        if (ConstantUtil.XSKYRESTORAGE) {
            if (file == null && fileString == null) {
                data.put("data", "没有相关的文件");
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("添加警告！").setData(data);
            }
            Belongings belongings = goodsService.addGoods2(file, fileString, suspectId);
            if (!StringUtil.isEmpty(belongings.getPicUrl())) {
                data.put("path", belongings.getPicUrl());
                data.put("id", belongings.getId());
                return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！").setData(data);
            } else {
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空)");
            }
        } else {
            String trueFileName = String.valueOf(System.currentTimeMillis());
            //文件夹地址
            String folderPath = ConstantUtil.PHOTO_PATH + "suspect" + File.separatorChar + "goods" + File.separatorChar;
            // 设置存放图片文件的路径
            File folderFile = new File(folderPath);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
            }
            try {
                if (file != null) {
                    String fileName = file.getOriginalFilename();// 文件原名称
                    // 自定义的文件名称
                    //获取文件类型
                    String fileType = fileName.substring(fileName.lastIndexOf("."));

                    String filePath = File.separatorChar + "suspect" + File.separatorChar + "goods" + File.separatorChar + trueFileName + fileType;//数据库存储地址
                    String path = folderPath + trueFileName + fileType;//磁盘存储路径地址
                    FileOutputStream out = new FileOutputStream(path);
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                    Belongings belongings = new Belongings();
                    // 转存文件到指定的路径
                    belongings.setSuspectId(suspectId);
                    belongings.setPicUrl(filePath);
                    String id = StringUtil.generatorUUID();
                    belongings.setId(id);
                    int value = goodsService.addGoods(belongings);
                    //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        data.put("value", 1);
                        data.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("新增嫌疑人随身物品成功");
                        appResult.setData(data);
                    } else {
                        data.put("value", 0);
                        appResult.setCode(-1);
                        appResult.setMsg("新增嫌疑人随身物品失败");
                        appResult.setData(data);
                    }
                    return appResult;
                } else if (!StringUtil.isEmpty(fileString) && fileString != "") {
                    //String truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));
                    String fileType = ".png";
                    String path = folderPath + trueFileName + fileType;//磁盘存储路径
                    String filePath = File.separatorChar + "suspect" + File.separatorChar + "goods" + File.separatorChar + trueFileName + fileType;//数据库存储地址

                    //Base64解码
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
                    byte[] b = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {//调整异常数据
                            b[i] += 256;
                        }
                    }

                    FileOutputStream out = new FileOutputStream(path);
                    out.write(b);
                    out.flush();
                    out.close();
                    Belongings belongings = new Belongings();
                    // 转存文件到指定的路径
                    belongings.setPicUrl(filePath);
                    belongings.setSuspectId(suspectId);
                    String id = StringUtil.generatorUUID();
                    belongings.setId(id);
                    int value = goodsService.addGoods(belongings);
                    //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        data.put("id", id);
                        data.put("value", 1);
                        data.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("新增嫌疑人随身物品成功!");
                        appResult.setData(data);
                    } else {
                        data.put("value", 0);
                        appResult.setCode(-1);
                        appResult.setMsg("新增嫌疑人随身物品失败!");
                        appResult.setData(data);
                    }
                    return appResult;
                }
            } catch (Exception e) {
                log.error("新增异常={}", e);
            }
            data.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("新增嫌疑人随身物品失败!");
            appResult.setData(data);
            return appResult;
        }
    }

    /**
     * @param belongings 根据嫌疑人id更新嫌疑人随身物品信息
     */
    @MyPower(name = "根据嫌疑人id更新嫌疑人随身物品信息", url = "/updateSuspectGoods")
    @RequestMapping("updateSuspectGoods")
    public AppResult updateSuspectGoods(@RequestBody Belongings belongings) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("id:{}", JSONObject.toJSONString(belongings));
        int value = goodsService.updateSuspectGoods(belongings);
        if (value > 0) {
            date.put("Value", 1);
            appResult.setCode(200);
            appResult.setMsg("随身物品更新成功!");
            appResult.setData(date);
        } else {
            date.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("随身物品更新失败!");
            appResult.setData(date);
        }
        return appResult;
    }


    /**
     * 随身物品记录删除
     */
    @MyPower(name = "随身物品记录删除", url = "/delGoods")
    @RequestMapping("delGoods")
    public AppResult delGoods(String id) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("id:{}", JSONObject.toJSONString(id));
        int value = goodsService.delGoods(id);
        if (value > 0) {
            date.put("Value", 1);
            appResult.setCode(200);
            appResult.setMsg("删除随身物品记录成功!");
            appResult.setData(date);
        } else {
            date.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("删除随身物品记录失败!");
            appResult.setData(date);
        }
        return appResult;
    }

    /**
     * 嫌疑人随身物品页面初始化
     *
     * @param suspectId
     * @return
     */
    @MyPower(name = "嫌疑人随身物品页面初始化", url = "/selectGoods")
    @RequestMapping("selectGoods")
    public AppResult selectGoods(String suspectId) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("selectGoods:{}", JSONObject.toJSONString(suspectId));
        List<Belongings> list = goodsService.selectGoods(suspectId);
        date.put("Value", list);
        appResult.setCode(200);
        appResult.setMsg("查询嫌疑人随身物品成功!");
        appResult.setData(date);
        return appResult;
    }

    /**
     * 随身物品暂扣
     */
    @MyPower(name = "随身物品暂扣", url = "/upDateZkGoods")
    @RequestMapping("upDateZkGoods")
    public AppResult upDateZkGoods(String id) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("id:{}", JSONObject.toJSONString(id));
        int value = goodsService.upDateZkGoods(id);
        if (value > 0) {
            date.put("Value", 1);
            appResult.setCode(200);
            appResult.setMsg("随身物品暂扣成功!");
            appResult.setData(date);
        } else {
            date.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("随身物品暂扣失败!");
            appResult.setData(date);
        }
        return appResult;
    }

    /**
     * 物品返还时信息状态改变
     */
    @MyPower(name = "物品返还时信息状态改变", url = "/updateByPrimaryKey")
    @RequestMapping("updateByPrimaryKey")
    public AppResult updateByPrimaryKey(@RequestBody Belongings belongings) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("belongings:{}", JSONObject.toJSONString(belongings));
        int value = goodsService.updateByPrimaryKey(belongings);
        if (value > 0) {
            date.put("Value", 1);
            appResult.setCode(200);
            appResult.setMsg("更新物品返还时信息状态成功");
            appResult.setData(date);
        } else {
            date.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("更新物品返还时信息状态失败");
            appResult.setData(date);
        }
        return appResult;
    }

    /**
     * 随身物品返还时照片存储
     */
    @MyPower(name = "随身物品返还时照片存储", url = "/upDateGoods")
    @RequestMapping("upDateGoods")
    public AppResult upDateGoods(MultipartFile file, String id, String fileString) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("file:{}", JSONObject.toJSONString(file));
        log.info("id:{}", JSONObject.toJSONString(id));
        // 获取当前时间毫秒数拼接
        if (ConstantUtil.XSKYRESTORAGE) {
            if (file == null && fileString == null) {
                date.put("data", "没有相关的文件");
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("添加警告！").setData(date);
            }
            if (goodsService.upDateGoods2(file, fileString, id) > 0) {

                return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！");
            } else {
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空)");
            }
        } else {
            String trueFileName = String.valueOf(System.currentTimeMillis());
            //生成的文件夹
            String folderPath = ConstantUtil.PHOTO_PATH + "suspect" + File.separatorChar + "returnGoods" + File.separatorChar;
            //File.separator+"data"+File.separator+"photo"+File.separator;
            //生成文件夹
            File folderFile = new File(folderPath);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
            }
            try {
                if (file != null) {
                    String fileName = file.getOriginalFilename();// 文件原名称
                    //截取文件后缀
                    String fileType = fileName.substring(fileName.lastIndexOf("."));

                    // 转存文件到指定的路径
                    String path = folderPath + trueFileName + fileType;//磁盘存储地址
                    String filePath = File.separatorChar + "suspect" + File.separatorChar + "returnGoods" + File.separatorChar + trueFileName + fileType;//数据库存储地址
                    FileOutputStream out = new FileOutputStream(path);
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                    int value = goodsService.upDateGoods(filePath, id);
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        date.put("value", 1);
                        date.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("新增随身物品返还时照片存储成功");
                        appResult.setData(date);
                    } else {
                        date.put("value", 0);
                        appResult.setCode(-1);
                        appResult.setMsg("新增随身物品返还时照片存储失败");
                        appResult.setData(date);
                    }
                    return appResult;
                } else if (fileString != null && fileString != "") {
//                String truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));
                    String fileType = ".png";
                    String path = folderPath + trueFileName + fileType;//磁盘存储路径
                    String filePath = File.separator + "suspect" + File.separatorChar + "returnGoods" + File.separatorChar + trueFileName + fileType;//数据库存储地址
                    //Base64解码
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
                    byte[] b = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < b.length; ++i) {
                        if (b[i] < 0) {//调整异常数据
                            b[i] += 256;
                        }
                    }

                    FileOutputStream out = new FileOutputStream(path);
                    out.write(b);
                    out.flush();
                    out.close();
                    int value = goodsService.upDateGoods(filePath, id);
                    String returnPath = ConstantUtil.SERVER_URL + filePath;
                    if (value > 0) {
                        date.put("value", 1);
                        date.put("returnPath", returnPath);
                        appResult.setCode(200);
                        appResult.setMsg("新增成功");
                        appResult.setData(date);
                    } else {
                        date.put("value", 0);
                        appResult.setCode(-1);
                        appResult.setMsg("新增失败");
                        appResult.setData(date);
                    }
                    return appResult;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            date.put("value", 0);
            appResult.setCode(-1);
            appResult.setMsg("新增失败");
            appResult.setData(date);
            return appResult;
        }
    }


    /**
     * 随身物品返回时视频存储
     */
    @MyPower(name = "随身物品返回时视频存储", url = "/upDateVdieoGoods")
    @RequestMapping("upDateVdieoGoods")
    public AppResult upDateVidieoGoods(@RequestBody MultipartFile file, String id, String fileString) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("file:{}", JSONObject.toJSONString(file));
        log.info("id:{}", JSONObject.toJSONString(id));
        // 获取当前时间毫秒数拼接
        String trueFileName = String.valueOf(System.currentTimeMillis());
        // 设置存放图片文件夹的路径
        String folderPath = ConstantUtil.PHOTO_PATH + File.separatorChar + "suspect" + File.separatorChar + "reVidieoGoods" + File.separatorChar;
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();// 文件原名称
                //截取文件后缀
                String fileType = fileName.substring(fileName.lastIndexOf("."));
                //System.out.print("folderPath------------->"+folderPath);
                // 创建文件夹
                File folderFile = new File(folderPath);
                if (!folderFile.exists()) {
                    folderFile.mkdirs();
                }
                String path = folderPath + trueFileName + fileType;//磁盘存储地址
                String filePath = File.separatorChar + "suspect" + File.separatorChar + "reVidieoGoods" + File.separatorChar + trueFileName + fileType;//数据库存储地址
                FileOutputStream out = new FileOutputStream(path);
                out.write(file.getBytes());
                out.flush();
                out.close();
                int value = goodsService.upDateVdieoGoods(filePath, id);
                String returnPath = ConstantUtil.SERVER_URL + filePath;
                if (value > 0) {
                    date.put("value", value);
                    date.put("returnPath", returnPath);
                    appResult.setCode(200);
                    appResult.setMsg("更新成功！");
                    appResult.setData(date);
                } else {
                    date.put("value", 0);
                    appResult.setCode(-1);
                    appResult.setMsg("更新失败！");
                    appResult.setData(date);
                }
                return appResult;
            } else if (fileString != null && fileString != "") {
                // String truefileType=fileString.substring(fileString.indexOf("/")+1,fileString.indexOf(";"));
                String fileType = ".png";
                String path = folderPath + trueFileName + fileType;//磁盘存储路径
                String filePath = File.separatorChar + "suspect" + File.separatorChar + "reVidieoGoods" + File.separatorChar + trueFileName + fileType;//数据库存储路径
                //Base64解码
                BASE64Decoder decoder = new BASE64Decoder();
                String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                log.info("Base64解码后:\n" + base64String);
                byte[] b = decoder.decodeBuffer(base64String);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {//调整异常数据
                        b[i] += 256;
                    }
                }

                FileOutputStream out = new FileOutputStream(path);
                out.write(b);
                out.flush();
                out.close();
                int value = goodsService.upDateVdieoGoods(filePath, id);
                String returnPath = ConstantUtil.SERVER_URL + filePath;
                if (value > 0) {
                    date.put("value", value);
                    date.put("returnPath", returnPath);
                    appResult.setCode(200);
                    appResult.setMsg("更新成功！");
                    appResult.setData(date);
                } else {
                    date.put("value", 0);
                    appResult.setCode(-1);
                    appResult.setMsg("更新失败！");
                    appResult.setData(date);
                }
                return appResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        date.put("value", 0);
        appResult.setCode(-1);
        appResult.setMsg("更新失败！");
        appResult.setData(date);
        return appResult;

    }

    /**
     * 物品返还查询所有
     */
    @MyPower(name = "物品返还查询所有", url = "/selectAll")
    @RequestMapping("selectAll")
    public AppResult selectAll(@RequestBody JSONObject queryCondition) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("user query...");
        //查询条件+分页
        int pageNum = queryCondition.getIntValue("pageNum");
        int pageSize = queryCondition.getIntValue("pageSize");
        Belongings belongings = new Belongings();
        belongings.setPage(pageNum, pageSize);
        belongings.setQueryCondition(queryCondition);
        List<Belongings> orderList = goodsService.selectAll(belongings);
        //用PageInfo对结果进行包装
        PageInfo<Belongings> pageInfo = new PageInfo<>(orderList);
        DataGrid dataGrid = new DataGrid(pageInfo.getTotal(), pageInfo.getList());
        data.put("datagrid", dataGrid);
        result.setCode(200);
        result.setMsg("query success");
        result.setData(data);
        return result;
    }

    /**
     * 打印所有物品
     *
     * @return
     */
    @MyPower(name = "打印所有物品", url = "/selectAllByType")
    @RequestMapping("selectAllByType")
    public AppResult selectAllByType(@RequestBody Belongings belongings) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("belongings:{}", JSONObject.toJSONString(belongings));
        String path = goodsService.selectAllByType(belongings);
        date.put("path", path);
        appResult.setCode(200);
        appResult.setMsg("打印成功");
        appResult.setData(date);
        return appResult;
    }


    /**
     * 根据id查询返还物品信息
     */
    @MyPower(name = "根据id查询返还物品信息", url = "/selectById")
    @RequestMapping(value = "selectById")
    public AppResult selectById(String id) {

        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("id:{}", JSONObject.toJSONString(id));
        Belongings belongings = goodsService.selectById(id);
        date.put("belongings", belongings);
        appResult.setCode(200);
        appResult.setMsg("select success");
        appResult.setData(date);
        return appResult;
    }

    /**
     * 物品返还打印pdf表格(打印3中状态的物品)
     */
    @MyPower(name = "物品返还生成pdf文件", url = "/goodsPrintByType")
    @RequestMapping("goodsPrintByType")
    public AppResult goodsPrintByType(@RequestBody Belongings belongings) {
        AppResult appResult = new AppResult();
        JSONObject date = new JSONObject();
        log.info("suspectId:{}", JSONObject.toJSONString(belongings));
        String str = goodsService.goodsPrintByType(belongings);
        if (!StringUtil.isEmpty(str)) {
            date.put("str", str);
            appResult.setCode(200);
            appResult.setMsg("print success");
            appResult.setData(date);
        } else {
            date.put("value", str);
            appResult.setCode(-1);
            appResult.setMsg("print null");
            appResult.setData(date);
        }
        return appResult;
    }

}